#!/usr/bin/env python
#-*- coding:utf-8 -*-
'''
处理后台分类目录
author:coldnight
email:coldnight.linux@gmail.com
'''

import re
from bottle import template, request, response
from bottle import route
from bottle import redirect
from model.auth import blog_auth
from model import model
from setting import TEMPLATE
from model.auth import blog_auth



TEMPLATE['BLOG_NAME'] = model.get_option('BLOG_NAME')
TEMPLATE['SUBTITLE'] = model.get_option('SUBTITLE')
TEMPLATE['ADMINMAIL'] = model.get_option('ADMINMAIL')


@route('/admin/categories:#/?#')
@blog_auth
def categories():
    '''
    创建一个页面用于显示类别,并管理类别
    '''

    try:
        del TEMPLATE['cate_edit']
    except:
        pass
    TEMPLATE['title']  = u'管理分类  | ' + TEMPLATE['BLOG_NAME']
    TEMPLATE['user'] = request.COOKIES.get('user', '')
    TEMPLATE['categories'] = model.get_categories()

    TEMPLATE['info'] = False
    TEMPLATE['error'] = False
    return template('admin-cate.html', TEMPLATE)



# 分类目录添加
@route('/admin/categories/add:#/?#', method='POST')
@blog_auth
def categories_add():
    '''
    将用户提交的分类目录插入数据库
    '''
    TEMPLATE['error'] = False
    cate_data = request.POST
    cate = cate_data['cate']
    model.category(cate)
    redirect('/admin/categories/')


# 批量删除分类目录
@route('/admin/categories/bulkdel', method="POST")
@blog_auth
def categories_bulkdel():
    '''
    批量删除分类目录
    '''
    TEMPLATE['info'] = False
    post_data = request.POST
    if post_data['dropdown'] == 'del':
        cate_ids = []
        for key in post_data.keys():
            if re.match(r'^cate-\d+',key):
                cate_ids.append(post_data[key])

        # 判断是否选中分类目录
        if cate_ids:
            model.category_del(cate_ids)
            TEMPLATE['error'] = False
        else:
            TEMPLATE['error'] = True
            TEMPLATE['errorinfo'] = '选要删除的分类目录'
    else:
        TEMPLATE['error'] = True
        TEMPLATE['errorinfo'] = '请选择一个操作'

    if TEMPLATE['error']:
        return template('admin-cate.html', TEMPLATE)
    else:
        redirect("/admin/categories")


# 单个删除分类目录
@route('/admin/categories/del/:id#(?:[0-9a-f]{24}|\d+)#')
@blog_auth
def categorie_del(id):
    model.category_del(id)
    redirect("/admin/categories")

# 编辑分类目录
@route('/admin/categories/edit/:id#(?:[0-9a-f]{24}|\d+)#')
@blog_auth
def categories_edit(id):
    cate = model.get_category(id)
    TEMPLATE['cate_edit'] = cate
    TEMPLATE['title'] = u'编辑分类目录'
    TEMPLATE['user'] = request.COOKIES.get('user', '')

    try:
        del TEMPLATE['info']
    except:
        pass
    return template('admin-cate.html', TEMPLATE)


# 处理更新分类目录
@route('/admin/categories/edit/post', method='POST')
@blog_auth
def categorries_edit_post():
    '''
    处理编辑分类的post请求
    '''
    edit_data = request.POST
    id = edit_data['cateid']
    name = edit_data['cate']
    model.category_edit(id, name)
    
    redirect("/admin/categories")
